import mysql.connector
from config import mysql_config

def create_tables():
    try:
        conn = mysql.connector.connect(**mysql_config)
        cursor = conn.cursor()
        
        with open('schema.sql', 'r', encoding='utf-8') as f:
            sql = f.read()
        
        # 分割SQL语句并逐条执行
        for statement in sql.split(';'):
            if len(statement.strip()) > 0:
                cursor.execute(statement)
        
        # 测试数据需要匹配最新表结构
        test_data_sql = """
        INSERT INTO blockchain_records 
        (data_type, data_content, data_hash, prev_hash, block_hash)
        VALUES 
        ('material', '{"batch_no":"B2023001"}', 'hash1', 'genesis', 'block1'),
        ('production', '{"line_id":"L02"}', 'hash2', 'block1', 'block2')
        """
        cursor.execute(test_data_sql)
        conn.commit()
        
        print('数据库表创建成功！')
        
    except Exception as e:
        print(f'创建数据库表时出错：{str(e)}')
        
    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()

if __name__ == '__main__':
    create_tables() 